package com.msxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msxt.dto.ChatMessage;
import com.msxt.dto.ZaixiankefuEntity;
import com.msxt.mapper.ChatMessageMapper;
import com.msxt.service.ChatMessageService;
import com.msxt.service.ZaixiankefuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service("chatMessageService")
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatMessageService {

    @Autowired
    private ZaixiankefuService zaixiankefuService;

    @Override
    public List<ChatMessage> getMessagesByConsultBianhao(String consultBianhao) {
        QueryWrapper<ChatMessage> wrapper = new QueryWrapper<>();
        wrapper.eq("consult_bianhao", consultBianhao)
                .orderByAsc("timestamp");
        return this.list(wrapper);
    }

    @Override
    @Transactional
    public Long saveMessage(ChatMessage message) {
        if ("heartbeat".equals(message.getMessageType()) || "heartbeat_ack".equals(message.getMessageType())) {
            return -1L;
        }

        // 关键修复：确保咨询记录存在
        if (StringUtils.isNotBlank(message.getConsultBianhao())) {
            QueryWrapper<ZaixiankefuEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("bianhao", message.getConsultBianhao());
            Long count = zaixiankefuService.count(wrapper);
            if (count == 0) {
                throw new RuntimeException("咨询记录不存在，咨询编号: " + message.getConsultBianhao());
            }
        }

        setDefaultValues(message);
        message.setCreateTime(new Date());
        this.saveOrUpdate(message);
        return message.getId();
    }

    private void setDefaultValues(ChatMessage message) {
        if (message.getSenderType() == null || message.getSenderType().isEmpty()) {
            message.setSenderType("system");
        }
        if (message.getSenderId() == null || message.getSenderId().isEmpty()) {
            message.setSenderId("unknown");
        }
        if (message.getSenderName() == null || message.getSenderName().isEmpty()) {
            if (!"unknown".equals(message.getSenderId())) {
                message.setSenderName("用户" + message.getSenderId());
            } else {
                message.setSenderName("未知用户");
            }
        }
        if (message.getContent() == null) {
            message.setContent("");
        }
        if (message.getMessageType() == null || message.getMessageType().isEmpty()) {
            message.setMessageType("text");
        }
        if (message.getTimestamp() == null) {
            message.setTimestamp(System.currentTimeMillis());
        }
        if (message.getIsRead() == null) {
            message.setIsRead(0);
        }
    }

    @Override
    public void markMessageAsRead(Long messageId, String readerId) {
        ChatMessage message = this.getById(messageId);
        if (message != null) {
            message.setIsRead(1);
            this.updateById(message);
        }
    }

    @Override
    public Long getUnreadCount(String consultBianhao, String userId) {
        QueryWrapper<ChatMessage> wrapper = new QueryWrapper<>();
        wrapper.eq("consult_bianhao", consultBianhao)
                .ne("sender_id", userId)
                .eq("is_read", 0);
        return this.count(wrapper);
    }
}